/**
 * Created by xxx on 2017年11月9日.
 */
/**
 * 表单组件
 * @type {*}
 */
var Table = React.createClass({
    render: function () {
        var deviceNmae = '智能学生证',peice = this.props.trData.price;
        if(this.props.trData.devicetype==8){
            deviceNmae = '13.56考勤卡';
            peice = this.props.trData.price;
        }else if(this.props.trData.devicetype==9){
            deviceNmae = '2.4考勤卡';
            peice = this.props.trData.price;
        }
        return (
            <tr>
                <td style={{width: '10%'}}>{parseInt(this.props.listNumber)+1}</td>
                <td style={{width: '20%'}}>{this.props.schoolname}</td>
                <td style={{width: '20%'}}>{deviceNmae}</td>
                <td style={{width: '15%'}}>{peice}</td>
                <td style={{width: '15%'}}>{this.props.trData.devicetype!='2'?<span>----</span>:this.props.trData.packagePrice}</td>
                <td style={{width: '20%'}}>
                    <div className='trButton trLeft clickDliver' onClick={this.props.onClickEdit}>修改</div>
                    <div className='trButton trLeft table-delete' onClick={this.props.onClickDelete}>删除</div>
                </td>
            </tr>
        );
    }
});
//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {
            tableData:[],
            schoolDataAll: [],
            schoolDataList: [],
            selectData: {},
            schoolname: '',
            popType: 0,//默认为0，1为编辑 2为新增
            deviceType: 2,//2 智能学生证 8 13.56考勤卡 9 2.4考勤卡
            deviceTypeList: [],
        }
    },
    componentDidMount: function () {
        var svar = this;
        this.getSchooleList();//获取所有学校
        //绑定回车时间
        $(document).keypress(function(e) {
            var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            if (eCode == 13){
                if($(".enterEvent").is(":focus")){
                    svar.toSearchClick();
                }
            }
        });
    },
    /**
     * 获取所有学校
     */
    getSchooleList: function () {
        var svar = this;
        suixun.showLoding();//显示加载中
        suixun.ajax(serverUrl+'/schoolManage/querySchool.json','',"get",function(data){//index:"'+this.state.bannerMenu+'",
            suixun.hideLoding(500);//显示加载中
            if(data.code == 200){
                if(data.info){
                    svar.setState({schoolDataList:data.info,schoolDataAll:data.info});
                }else{
                    svar.setState({tableData:[]});
                }
            }else{
                suixun.alert(data.msg);
            }
        });
    },
    /**
     * 查询学校价格
     */
    getSystemPrice: function (schoolName) {
        var svar = this;
        suixun.showLoding();//显示加载中
        var deviceTypeList = [
            {value:'2',name:'智能学生证',selected:''},
            {value:'8',name:'13.56考勤卡',selected:''},
            {value:'9',name:'2.4G考勤卡',selected:''}
        ],deviceType = 2;
        suixun.ajax(serverUrl+'/devicePriceManage/getSchoolPrices?schoolName='+schoolName,'',"get",function(data){//index:"'+this.state.bannerMenu+'",
            suixun.hideLoding(500);//显示加载中
            if(data.code == 200){
                if(data.info){
                    for(var i = 0;i<data.info.length;i++){
                        deviceTypeList.splice(svar.getArrayIndex(deviceTypeList,'value',data.info[i].devicetype),1);
                    }
                    if(deviceTypeList.length>0){
                        deviceTypeList[0].selected='selected';
                        deviceType = deviceTypeList[0].value
                    }
                    svar.setState({tableData:data.info,deviceTypeList:deviceTypeList,deviceType: deviceType});
                }else{
                    deviceTypeList[0].selected='selected';
                    svar.setState({tableData:[],deviceTypeList:deviceTypeList,deviceType:deviceType});
                    // $("#deviceType")
                }
            }else{
                suixun.alert(data.msg,function (data) {
                    if(data){
                        deviceTypeList[0].selected='selected';
                        svar.setState({tableData:[],deviceTypeList:deviceTypeList,deviceType:deviceType});
                    }
                });
            }
        });
    },
    /**
     * 更具元素获取数组所在位置
     */
    getArrayIndex: function (array,key,value) {
        var index = 0;
        for(var i = 0;i<array.length;i++){
            if(array[i][key]==value){
                index = i;
                break;
            }
        }
        return index;
    },
    /**
     * 显示修改价格页面
     * @param info
     * @returns {XML}
     */
    onClickEdit: function (info) {
        var deviceNmae = '智能学生证',peice = info.price,packagePrice = '';
        if(info.devicetype==8){
            deviceNmae = '13.56考勤卡';
            peice = info.price;
        }else if(info.devicetype==9){
            deviceNmae = '2.4考勤卡';
            peice = info.price;
        }
        if(info.packagePrice>0){
            packagePrice = info.packagePrice;
        }
        $('.textDeviceType').html(deviceNmae);
        $('#price').val(peice);
        $('#packagePrice').val(packagePrice);
        this.setState({selectData:info,popType: 1});
        $(".popModel").show();
    },
    /**
     * 新增学校价格
     */
    addPrice: function () {
        if(this.state.schoolname){
            this.setState({popType: 2});
            $(".popModel").show();
        }else{
            suixun.alert('请选择学校！');
        }
    },
    /**
     * 删除该设备价格
     * @param info
     */
    onClickDelete: function (info) {
        var svar = this;
        suixun.confirm_noTit('确定删除该设备价格？',function (data) {
            if(data){
                var data = new FormData();
                data.append("schoolName",svar.state.schoolname);
                data.append("deviceType",info.devicetype);
                suixun.showLoding();//显示加载中
                suixun.ajax(serverUrl+'/devicePriceManage/deleteSchoolPrices',data,"post",function(data){
                    suixun.hideLoding();//隐藏加载中
                    if(data.code == 200){
                        suixun.alert('操作成功!',function (data) {
                            if(data){
                                svar.getSystemPrice(svar.state.schoolname);
                            }
                        });
                    }else{
                        suixun.alert(data.msg);
                    }
                });
            }
        });
    },
    /**
     * 设置价格
     */
    setDevicePrice: function () {
        var svar = this;
        var price = $('#price').val();//硬件价格
        var packagePrice = $('#packagePrice').val();//硬件套餐价格
        var schoolName = svar.state.selectData.schoolName;
        var url  = serverUrl+'/devicePriceManage/updateSchoolPrice';
        var data = new FormData();
        data.append("schoolName",this.state.schoolname);
        if(price==''){
            suixun.alert('硬件价格不能为空！');
            return;
        }
        if(!this.judgePrice(price)){
            suixun.alert('请输入正确的硬件价格！');
            return;
        }
        if(this.state.popType==1){//编辑
            if(this.state.selectData.devicetype==2){
                if(packagePrice == ''){
                    suixun.alert('套餐价格不能为空！');
                    return;
                }else if(!this.judgePrice(packagePrice)){
                    suixun.alert('请输入正确的套餐价格！');
                    return;
                }
                data.append("smartCardPrice",price);
                data.append("packagePrice",packagePrice);
            }else {
                if(packagePrice != '' && !this.judgePrice(packagePrice)){
                    suixun.alert('请输入正确的套餐价格！');
                    return;
                }
                if(this.state.selectData.devicetype==8){
                    data.append("whiteCard13_56Price",price);
                }
                if(this.state.selectData.devicetype==9){
                    data.append("whiteCard2_4Price",price);
                }
            }
        }else{//新增
            url = serverUrl+'/devicePriceManage/saveSchoolPrice';
            if(this.state.deviceType==2){
                if(packagePrice == ''){
                    suixun.alert('套餐价格不能为空！');
                    return;
                }else if(!this.judgePrice(packagePrice)){
                    suixun.alert('请输入正确的套餐价格！');
                    return;
                }
                data.append("smartCardPrice",price);
                data.append("packagePrice",packagePrice);
            }else{
                if(packagePrice != '' && !this.judgePrice(packagePrice)){
                    suixun.alert('请输入正确的套餐价格！');
                    return;
                }
                if(this.state.deviceType == 8){
                    data.append("whiteCard13_56Price",price);
                }
                if(this.state.deviceType == 9){
                    data.append("whiteCard2_4Price",price);
                }
            }
        }
        suixun.showLoding();//显示加载中
        suixun.ajax( url, data, "post", function(data){
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                suixun.alert('操作成功!',function (data) {
                    if(data){
                        svar.getSystemPrice(svar.state.schoolname);
                        svar.onClickHidePop();
                        $('#price').val('');//硬件价格
                        $('#packagePrice').val('');//硬件套餐价格
                    }
                });
            }else{
                suixun.alert(data.msg);
            }
        });
    },
    /**
     * 关闭修改价格弹出框
     */
    onClickHidePop: function () {
        $(".popModel").hide();
        $(".errorMsg").hide();
    },
    /**
     * 验证金额
     * @param e
     */
    onChangePrice: function (e) {
        if(this.judgePrice(e.target.value)||e.target.value==''){
            $("."+e.target.getAttribute('data-error')+"").hide();
        }else{
            $("."+e.target.getAttribute('data-error')+"").show();
        }
    },
    /**
     * 价格验证
     * @param value
     * @return boolean
     */
    judgePrice: function (value) {
        var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        if(!reg.test(value)){
            return false;
        }else{
            return true;
        }

    },

    /**
     * 点击学校名称列表
     * @param info
     */
    onClickSchoolList: function (info) {
        $("#select-by-conditions").html("已激活");
        $(".queryImei").val("");//制空IMEI搜索框
        // otherData.status = "2";
        // otherData.schoolname = info[0];
        // otherData.schoolid = info[0];
        this.setState({schoolname:info.schoolname});
        this.getSystemPrice(info.schoolname);//查询左侧
    },
    /**
     * 点击全部
     * @param e
     */
    onClickAll: function (e) {
        $("#select-by-conditions").html("已激活");
        $(".list-number-span").addClass(" select");
        $(".list-data-li").siblings().removeClass(" select");
        $(".queryImei").val("");//制空IMEI搜索框
        $("#querySchool").val("");//制空学校搜索框
        // otherData.schoolname = "";
        // otherData.status = "2";
        // this.setState({otherData:otherData});
        // this.getSystemPrice(info[0]);//查询左侧
        this.setState({schoolname: '',tableData: []});
    },
    /**
     * 点击左边的搜索
     */
    toSearchClick:function () {
        var querySchool = $("#querySchool").val();
        var schoolDataList = [];
        $(".queryImei").val("");//制空IMEI搜索框
        for(var i = 0;i < this.state.schoolDataAll.length;i++){//看批号数据里面有没有输入的批号
            if(this.state.schoolDataAll[i].schoolname == querySchool){
                schoolDataList.push({schoolname:this.state.schoolDataAll[i].schoolname,id:this.state.schoolDataAll[i].id});
                $(".querySchool").hide();//隐藏批号列表
                var listDataUl = $(".list-data-ul").children();//批号列表
                for(var j = 0;j<listDataUl.length;j++){
                    if($(listDataUl[j]).find(".list-number").html() == querySchool){
                        $('#left-body').animate({
                            scrollTop: i*25//
                        }, 100);
                        $(".list-data-div").siblings().removeClass(" select");
                        $(".list-number-span").removeClass(" select");//全部按钮
                        $(listDataUl[j]).addClass(" select").siblings().removeClass(" select");
                        $(".list-data-div-ul").show();
                        // otherData.schoolname = querySchool;
                        // otherData.schoolid = querySchool;
                        // this.setState({otherData:otherData});
                        // this.onQueryDatas(1);//查询左侧
                        this.setState({schoolname:querySchool});
                        this.getSystemPrice(querySchool);//查询左侧
                        break;
                    }
                }
                return;
            }
        }
    },
    /**
     * 改变弹出层学校输入框
     * @param e
     */
    onChangSchoolInput: function(e) {
        var val = $(e.target).val();
        if(val != ""){
            this.schoolArray(val,$(e.target).attr("data-list"));
        }else{
            $("."+$(e.target).attr("data-list")+"").hide();
        }
    },
    /**
     * 排序
     * @param val
     * @param cls
     */
    schoolArray: function (val,cls) {
        var schoolDataList = [];
        for(var i = 0;i < this.state.schoolDataAll.length;i++){
            if((this.state.schoolDataAll[i].schoolname).indexOf(val) >= 0){
                schoolDataList.push({schoolname:this.state.schoolDataAll[i].schoolname,id:this.state.schoolDataAll[i].id});
            }
        }
        if(schoolDataList.length == 0){
            $("."+cls+"").hide();
        }else{
            $("."+cls+"").show();
            this.setState({schoolDataList:schoolDataList});
        }
    },
    /**
     * 点击学校输入框
     * @param e
     */
    onClickSchool: function (e) {
        var val = $(e.target).val();
        this.schoolArray(val,$(e.target).attr("data-list"));
    },
    /**
     * 点击左侧搜索框展开学校列表
     * @type {*}
     */
    onClickBachIdList: function (data) {
        $("#querySchool").val(data.schoolname);
        $(".querySchool").hide();//隐藏批号列表
        $(".queryImei").val("");//制空IMEI搜索框
        var listDataUl = $(".list-data-ul").children();//批号列表
        for(var i = 0;i<listDataUl.length;i++){
            if($(listDataUl[i]).find(".list-number").html() == data.schoolname){
                $('#left-body').animate({
                    scrollTop: i*25//
                }, 100);
                $(".list-number-span").removeClass(" select");//全部按钮
                $(".list-data-div").siblings().removeClass(" select");
                $(listDataUl[i]).addClass(" select").siblings().removeClass(" select");
                $(".list-data-div-ul").show();
                //设置批号编号
                // otherData.schoolname = target.html();
                // otherData.schoolid = target.html();
                // this.setState({otherData:otherData});
                // this.onQueryDatas(1);//查询左侧
                this.getSystemPrice(data.schoolname);//查询左侧
                this.setState({schoolname:data.schoolname});
                break;
            }
        }
    },
    /**
     * 新增设备价格改变设备类型
     */
    changeDeviceType: function () {
        this.setState({deviceType:$("#deviceType").val()});
    },
    render: function () {
        {
            var svar = this;
            var onClickArray = [this.onClickEdit,this.onClickDelete];
            var Tabels = this.state.tableData.map(function (data,index) {
                return (
                    <Table key={data.bannerId} onClickEdit={onClickArray[0].bind(svar,data)} onClickDelete={onClickArray[1].bind(svar,data)} listNumber={index} trData={data} schoolname={svar.state.schoolname}/>
                )
            });
            var listDatas = this.state.schoolDataAll.map(function (data) {
                return (
                    <li className="list-data-li" >
                        <span className="list-number" onClick={svar.onClickSchoolList.bind(svar,data)} title={data.schoolname}>{data.schoolname}</span>
                    </li>
                )
            });
        }
        return (
            <div className="tableManage-body schoolPrice">
                <div  className="popPhone popModel">
                    <div className="model"></div>
                    <div className="popModel-info">
                        <div className="popModel-title">
                            <span className="popModel-title-content">
                                <span className="popModel-title-content-solid-left"/>
                                    {this.state.popType==1?'修改设备价格':'新增设备价格'}
                                <span className="popModel-title-content-solid-right"/>
                            </span>
                            <span className="popModel-title-img" onClick={this.onClickHidePop}><img src="../img/icon/close.png" alt="关闭"/></span>
                        </div>
                        <div className="popModel-body">
                            <div className="popModel-body-imei" style={this.state.popType==1?{display:'block'}:{display:'none'}}>
                                <span className="popModel-body-imei-title">设备类型</span>
                                <span className="popModel-body-imei-content textDeviceType"></span>
                            </div>
                            {
                                this.state.popType!=1?
                                    <div className="popModel-body-input select-type" >
                                        <span className="popModel-body-input-title">设备类型</span>
                                        <span className="popModel-body-input-content" >
                                            <select  name="type" id="deviceType" value={this.state.deviceType} onChange={this.changeDeviceType}>
                                                {
                                                    svar.state.deviceTypeList.map(function(data){
                                                        return (
                                                            <option value={data.value} >{data.name}</option>
                                                        )
                                                    })
                                                }
                                            </select>
                                        </span>
                                    </div>
                                    :''
                            }
                            <div className="popModel-body-phone popModel-body-input">
                                <span className="popModel-body-phone-title popModel-body-input-title">硬件价格</span>
                                <span className="popModel-body-phone-id popModel-body-input-id" style={{display:'none'}}/>
                                <span className="popModel-body-phone-content popModel-body-input-content">
                                    <input className="phone-content input-content " id="price" type="text" maxLength='20' data-error="changePrice" placeholder="请输入金额" onChange={this.onChangePrice} />
                                </span>
                                <div className="errorMsg changePrice" />
                            </div>
                            <div className="popModel-body-phone popModel-body-input">
                                {
                                    this.state.popType==1?
                                        <span className={this.state.selectData.devicetype!=2?"popModel-body-phone-title popModel-body-input-title noImg":"popModel-body-phone-title popModel-body-input-title"}>套餐价格</span>
                                        :
                                        <span className={this.state.deviceType==2?"popModel-body-phone-title popModel-body-input-title":"popModel-body-phone-title popModel-body-input-title noImg"}>套餐价格</span>
                                }
                                <span className="popModel-body-phone-id popModel-body-input-id" style={{display:'none'}}/>
                                <span className="popModel-body-phone-content popModel-body-input-content">
                                    <input className="phone-content input-content " id="packagePrice" type="text" data-error="changePackagePrice" maxLength='20' placeholder="请输入金额" onChange={this.onChangePrice} />
                                </span>
                                <div className="errorMsg changePackagePrice" />
                            </div>
                        </div>
                        <div className="popModel-button">
                            <span className="popModel-button-ok" onClick={this.setDevicePrice}>确定</span>
                        </div>
                    </div>
                </div>
                <header>
                    <div className="header-left">
                        <div className="header-left-studentInfo">
                            <a href="./getSystemPrice.html" className="header-left-button menu-width  ">默认价格</a>
                            <a href="./schoolPrice.html" className="header-left-button showOrder">学校价格</a>
                            <a href="./devicePrice.html" className="header-left-button ">设备价格</a>
                        </div>
                        <div className="header-left-annotationsInfo">
                            <img src="../img/icon/annotations.png" />
                            <span className="header-left-annotations-arrowsLeft"/>
                            <div className="header-left-annotations">这里是注释。</div>
                        </div>
                    </div>
                    {
                        this.state.deviceTypeList.length>0?
                            <div className="header-right">
                                <div className="add-article" onClick={this.addPrice.bind(this)}>
                                    <img src="../img/icon/add-white.png" />
                                    <span>新增</span>
                                </div>
                            </div>
                            :''
                    }

                </header>
                <div id="content-left">
                    <div id="left-head">
                        <div id="left-search">
                            <div id="left-search-select">
                                <div id="school-or-address" ref="divValue">学校</div>
                                {/*<div id="school-or-address" className="selectByCondition" ref="divValue">学校</div>*/}
                            </div>
                            <div id="left-search-query">
                                <div id="left-search-query-input">
                                    <input type="text" className="queryVal enterEvent" onChange={this.onChangSchoolInput} onClick={this.onClickSchool} data-list="querySchool" id="querySchool" maxLength="50"  placeholder="请输入学校关键字" ref="inputValue"/>
                                </div>
                                <div id="left-search-query-img" onClick={this.toSearchClick}></div>
                                <div className="schoolList querySchool">
                                    {
                                        this.state.schoolDataList.map(function (data) {
                                            return (
                                                <span onClick={svar.onClickBachIdList.bind(svar,data)} className="schoolList-value querySchool-val" data-id={data.id}>{data.schoolname}</span>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="left-body" style={{height:'619px'}}>
                        <div id="left-body-contents">
                            <div className="list-show-total">
                                <span className="list-number-span select" onClick={this.onClickAll} >全部</span>
                            </div>
                            <div className="list-data">
                                <ul className="list-data-ul">
                                    {listDatas}
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="content-right">
                    <div id="right-head" >
                        <div id="right-body">
                            <div className="tableInfo tableInfo-change">
                                <div className="studentsInfo-data tableInfo-data">
                                    <div id="studentsInfo-data-table" className="studentsInfo-data-table tableInfo-data-table" >
                                        <table className="head-body">
                                            <thead>
                                                <th style={{width: '10%'}}>序号</th>
                                                <th style={{width: '20%'}}>学校名称</th>
                                                <th style={{width: '20%'}}>设备类型</th>
                                                <th style={{width: '15%'}}>硬件价格</th>
                                                <th style={{width: '15%'}}>套餐价格</th>
                                                <th style={{width: '20%'}}>操作</th>
                                            </thead>
                                            <tbody>
                                            {
                                                this.state.tableData.length==0?'':Tabels
                                            }
                                            </tbody>
                                        </table>
                                        {
                                            this.state.tableData == 0?<div className="tableNoData">{tableNoDataCount}</div>:''
                                        }
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        );
    }
});
ReactDOM.render(
    <Main />,
    document.getElementById('tableManage')
);
$(window).resize(function () {
    leftList();
});
$(function () {
    setTimeout(function () {
        leftList();
    },500);
    setTimeout(function () {
        leftList();
    },2000);
});
function leftList(){
    if($("#studentsInfo-data-table").height()+77 > $(window).height()){
        $("#left-body").css("height",$("#studentsInfo-data-table").height()+77-30+"px");
    }else{
        $("#left-body").css("height",$(window).height()-260+"px");
    }
}
//学校下拉列表
$("*").bind("click",function(e){
    var target = $(e.target);
    if(target.closest(".popQuerySchool-val").length == 1){
        $(".popQuerySchool").hide();
        $("#pop-schoolName").val(target.html());
    }else{
        $(".schoolList").hide();
    }
    if(target.closest(".querySchool-val").length == 1){

    }else{
        $(".schoolList").hide();
    }
    if(target.closest(".city-tab-list").length == 1 || target.closest(".addresses-item-center").length == 1 || target.closest(".addresses-content").length == 1 ){

    }else{
        $(".addressesOne").hide();
    }
});
//点击学校名称
$(".list-data-ul").on("click",".list-number",function () {
    $($(this).parent()).addClass(" select").siblings().removeClass(" select");
    $(".list-number-span").removeClass(" select");
});